<template>
  <view class="page">
    <view
      class="login-content"
      :class="`${isLogin ? 'active' : ''}`"
    >
      <view
        class="login-page"
        :class="`${isLogin ? 'login-logo-active' : ''}`"
      >
        <view class="login-logo">
          <!-- <img :src="require('../../img/logozhanwei.png')" />  -->
        </view>
        <view
          class="login-title"
          v-if="!isLogin"
        >
          <!-- <img :src="require('../../img/logozhanwei.png')" />  -->
        </view>
        <view
          class="login-text"
          v-if="!isLogin"
          >新一代云端办公平台</view
        >
      </view>
      <view
        class="login-button"
        :class="`${isLogin ? 'active' : ''}`"
      >
        <nut-button
          class="login-button-item"
          :class="`${isLogin && userName != '' && passWrod ? 'active' : ''}`"
          :type="isLogin ? 'default' : 'info'"
          @click="loginIn"
        >
          登录
        </nut-button>
        <view
          class="register"
          v-if="isLogin"
          >还没有账号？<text style="color: #1e74fd">立即注册</text></view
        >
        <nut-button
          type="default"
          v-if="!isLogin"
          >注册</nut-button
        >
        <view
          class="login-wecat"
          v-if="isLogin"
        >
          <view
            class="login-wecat-text"
            @click="handleWechatLogin()"
          >
            <button
              open-type="getPhoneNumber"
              @getphonenumber="handleGetPhone"
            >
              <i class="iconfont icon-weixin"></i>
              <text>微信登录</text>
            </button>
          </view>
        </view>
      </view>
      <view
        class="login-form"
        v-if="isLogin"
        :class="`${isLogin ? 'login-form-active' : ''}`"
      >
        <view class="login-form-tab">
          <view
            class="login-form-tab-item"
            @click="handleLoginMethod(1)"
            :class="`${accountLogin ? 'active' : ''}`"
            >密码登录</view
          >
          <nut-divider
            style="margin: 0 40rpx"
            direction="vertical"
          />
          <view
            class="login-form-tab-item"
            @click="handleLoginMethod(2)"
            :class="`${verificationLogin ? 'active' : ''}`"
            >验证码登录</view
          >
        </view>
        <view class="login-form-input">
          <view class="login-form-input-item">
            <nut-input
              v-model="userName"
              placeholder="请输入账号/手机号"
              class="input-userName"
            />
          </view>
          <view
            class="login-form-input-item"
            v-if="accountLogin"
          >
            <nut-input
              v-model="passWrod"
              placeholder="请输入密码"
              class="input-password"
            />
            <view class="forget-password">忘记密码</view>
          </view>
          <view
            class="login-form-input-item input-verification-password"
            v-if="verificationLogin"
          >
            <nut-input
              v-model="val"
              placeholder="请输入验证码"
              class="input-password"
            />
            <nut-button
              :type="buttonType"
              :disabled="isCounting"
              @click="handleGetCaptcha"
              size="mini"
            >
              {{ buttonText }}
            </nut-button>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onUnmounted } from "vue";
import Taro, { showToast, navigateTo } from "@tarojs/taro";
import { getLoginSession, getLoginPhone, getUserInfo, getAttendanceRecordQueryData } from "@/api/index";
import { wechatLogin } from "@/libs/wechat/runtime/index";
import { formatDates } from "@/utils/utils";

import { userInfoStore } from "@/stores/userInfoStore";
const store = userInfoStore();
const userPhone = ref("");
const punchCards = ref(""); // 是否打卡的数据
// 倒计时总时长（秒）
const COUNT_DOWN_TIME = 60;

// 响应式数据
const countDown = ref(0);
const timer = ref(null);
const val = ref("");
const userName = ref("");
const passWrod = ref("");
// 计算属性
const isCounting = computed(() => countDown.value > 0);
const buttonText = computed(() => (isCounting.value ? `${countDown.value}秒后重新获取` : "获取验证码"));
const buttonType = computed(() => (isCounting.value ? "default" : "info"));
// 微信登录
const handleWechatLogin = async () => {
  await wechatLogin().then(res => {
    getLoginSession({
      code: res.code,
    }).then(res => {
      console.log("登录成功66:", res.data);
      Taro.setStorageSync("sessionKey", res.data.sessionKey);
    });
  });
};
// 获取手机号
const handleGetPhone = async e => {
  console.log(e, "e");
  if (e.detail.errMsg === "getPhoneNumber:ok") {
    getLoginPhone({
      sessionKey: Taro.getStorageSync("sessionKey"),
      encryptedData: e.detail.encryptedData,
      iv: e.detail.iv,
    })
      .then(async res => {
        userPhone.value = res.data.phoneNumber;
        Taro.setStorageSync("token", res.data.access_token);
        Taro.setStorageSync("clientid", res.data.client_id);
        // Taro.setStorageSync("userInfo", res.data);
        await store.getUserInfo(); //user
        showToast({ title: "登录成功", icon: "none" });
        // 登录成功后刷新页面
        let params = {
          userId: Taro.getStorageSync("user").userId,
          date: formatDates(new Date()),
        };
        getAttendanceRecordQueryData(params).then(res => {
          if (res.code == 200) {
            punchCards.value = res.data;
            store.punchCards = res.data;
            // 如果当天没有打卡，则跳转到打卡页面
            Taro.reLaunch({
              url: "/pages/index/index",
            });
            if (res.data.checkInTime == null && res.data.checkOutTime == null) {
              // navigateTo({
              //   url: "/packageC/pages/checkIn/index",
              // });
            }
          } else {
          }
        });
      })
      .catch(err => {
        showToast({ title: err.msg, icon: "none" });
      });
  }
};
// 获取验证码方法
const handleGetCaptcha = async () => {
  if (isCounting.value) return;

  try {
    // 这里可以添加发送验证码的逻辑
    // 例如调用API接口
    // await sendCaptchaApi()

    showToast({
      title: "验证码已发送",
      icon: "success",
      duration: 2000,
    });

    // 开始倒计时
    startCountDown();
  } catch (error) {
    showToast({
      title: "发送失败，请重试",
      icon: "error",
      duration: 2000,
    });
    console.error("发送验证码失败:", error);
  }
};

// 开始倒计时
const startCountDown = () => {
  countDown.value = COUNT_DOWN_TIME;

  timer.value = setInterval(() => {
    countDown.value--;

    if (countDown.value <= 0) {
      clearInterval(timer.value);
      timer.value = null;
    }
  }, 1000);
};

// 组件卸载时清除定时器
onUnmounted(() => {
  if (timer.value) {
    clearInterval(timer.value);
    timer.value = null;
  }
});
const isLogin = ref(false);
const accountLogin = ref(true); // 账号登录
const verificationLogin = ref(false); // 验证码登录
const loginIn = () => {
  console.log("登录");
  isLogin.value = true;
  if (isLogin && userName.value != "" && passWrod.value != "") {
    // navigateTo({ url: "/pages/index/index" });
  }
};
const handleLoginMethod = (type: number) => {
  accountLogin.value = true;
  passWrod.value = "";
  accountLogin.value = type === 1;
  verificationLogin.value = type === 2;
};
</script>

<style lang="less">
@import "./index.less";
</style>
